package com.xym.manage.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xym.manage.pojo.PicUpLoadResult;
import com.xym.manage.service.PropertiesService;

//Request URL:http://manage.xym.com/rest/pic/upload?dir=image
@RequestMapping(value="pic")
@Controller
public class PicUpLoadController {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(PicUpLoadController.class);
	
	// JacksonJson中的序列化工具
	private static final ObjectMapper objectMapper = new ObjectMapper();
	
	// 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[] { ".bmp", ".jpg", ".jpeg", ".gif", ".png" };
    
    @Autowired
    private PropertiesService propertiesService;
    
/*    //图片上传后存放硬盘的位置
    @Value("${REPOSITORY_PATH}")
    private String REPOSITORY_PATH;
    
    //图片回显映射位置，使用nignx
    @Value("${IMAGE_BASE_URL}")
    private String IMAGE_BASE_URL;*/
	
	/**
	 * 图片上传
	 * @param uploadFile
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="upload",method=RequestMethod.POST,produces=MediaType.TEXT_PLAIN_VALUE)
	public String upLoadz(@RequestParam(value="uploadFile")MultipartFile uploadFile) throws Exception{
		
		// 校验图片格式
		boolean flag = false;
		//判断格式
		for (String type : IMAGE_TYPE) {
			if(StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)){
				flag = true;
				break;
			}
		}
		
		PicUpLoadResult result = new PicUpLoadResult();
		String filePath = getFilePath(uploadFile.getOriginalFilename());
		
		 if (LOGGER.isDebugEnabled()) {
	            LOGGER.debug("Pic file upload .[{}] to [{}] .", uploadFile.getOriginalFilename(), filePath);
	        }
		
		// 生成图片的绝对引用地址（URL地址）
	        String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath, propertiesService.REPOSITORY_PATH), "\\", "/");
	        result.setUrl(propertiesService.IMAGE_BASE_URL + picUrl);

	        File newFile = new File(filePath);

	        // 写文件到磁盘
	        uploadFile.transferTo(newFile);

	        // 校验图片是否合法
	        flag = false;
	        try {
	            BufferedImage image = ImageIO.read(newFile);
	            if (image != null) {
	                // 获取图片宽和高
	                result.setWidth(image.getWidth() + "");
	                result.setHeight(image.getHeight() + "");
	                // 一切正常则代表合法
	                flag = true;
	            }
	        } catch (IOException e) {
	        }

	        // 设置返回状态
	        result.setError(flag ? 0 : 1);

	        if (!flag) {
	            // 不合法，将磁盘上的文件删除
	            newFile.delete();
	        }
	        // 将返回结果对象转为JSON字符串返回
	        return objectMapper.writeValueAsString(result);
	    }

	    private String getFilePath(String sourceFileName) {
	        String baseFolder = propertiesService.REPOSITORY_PATH + File.separator + "images";
	        Date nowDate = new Date();
	        // 根据年月日：生成yyyy/MM/dd的目录结构
	        String fileFolder = baseFolder + File.separator + new DateTime(nowDate).toString("yyyy" + File.separator + "MM" + File.separator + "dd" );
	        File file = new File(fileFolder);
	        // 如果目录不存在，则创建目录
	        if (!file.exists()) {
	            file.mkdirs();
	        }
	        // 生成新的文件名
	        String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS")
	                + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");
	        // 返回文件的全路径
	        return fileFolder + File.separator + fileName;
	}
	
	  
   
}
